package com.comac.print.component.app.utils;

import com.alibaba.fastjson.JSONObject;
import com.comac.print.component.app.common.exception.PrintCommonException;
import com.comac.print.component.app.domain.gateway.constant.CommonConstant;
import com.itextpdf.kernel.geom.PageSize;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Objects;
import java.util.UUID;

/**
 * @author wanghuanwei_502226
 * @date 2025/4/11
 */
@Component
@Slf4j
public class Html2PdfUtils {
    /**
     * 下载转换之后的pdf时的URI模板，其中需要替换的是请求转换时传入的${key}对应的值
     */
    private static final String PDF_DOWNLOAD_URL_TPL = "/cache/files/data/conv_%s_pdf/output.pdf";

    private static final String HTML_STR_PATH = "/MOM2/PDF_CONVERT/HTML/";
    
    @Value("${onlyOffice.pdf.convertUrl:}")
    private String convertUrl;
    @Value("${onlyOffice.pdf.downloadHost:}")
    private String downloadHost;
    @Resource
    private MinIOFileUtil minIOFileUtil;

    public byte[] convertWithOnlyOffice(String htmlStr,String systemId, String bussinessId) {
        String htmlStrTempObjectKey = HTML_STR_PATH + UUID.randomUUID().toString().toUpperCase().replace("-", "");
        String htmlUrl = minIOFileUtil.uploadBytes(htmlStr.getBytes(), htmlStrTempObjectKey);
        if (StringUtils.isBlank(htmlUrl)) {
            log.error("upload html content to minio fail");
            throw new PrintCommonException("上传 html content 失败");
        }

        String key = UUID.randomUUID().toString();
        String pdfUrl = "";

        String pageSize = pageSize(systemId, bussinessId);
        String tmpTitle = UUID.randomUUID().toString().toUpperCase().replace("-", "") + "htmlConvertTemp";
        JSONObject convertParam = new JSONObject();
        convertParam.put("async", Boolean.FALSE);
        convertParam.put("filetype", "html");
        convertParam.put("key", key);
        convertParam.put("outputtype", "pdf");
        convertParam.put("title", tmpTitle);
        convertParam.put("url", htmlUrl);
        JSONObject parameters = new JSONObject();
        parameters.put("pageSize", pageSize);
        convertParam.put("parameters", parameters);
        try {
            String convertResult = HttpCustomUtil.doPost(convertUrl, convertParam);
            JSONObject result = JSONObject.parseObject(convertResult);
            log.info("convert finish,the result is:{}", result);
            pdfUrl = result.getString("fileUrl");

        } catch (Exception e) {
            log.error("convert html fail", e);
            throw new PrintCommonException("转换html失败");
        }

        if (StringUtils.isBlank(pdfUrl)) {
            log.error("convert finish,the url is blank");
            throw new PrintCommonException("转换pdf成功, 未获取到url地址");
        }

        String url = downloadHost + String.format(PDF_DOWNLOAD_URL_TPL, key);
        byte[] bytes = HttpCustomUtil.downloadFile(url);
        if (Objects.isNull(bytes)){
            log.error("pdf下载失败:{}", url);
            throw new PrintCommonException("pdf下载失败");
        }
        return bytes;
    }

    private String pageSize(String systemId, String bussinessId){
        String pageSize = "A4";
        if (StringUtils.isNotBlank(bussinessId) && StringUtils.isNotBlank(systemId)){
            if (StringUtils.equals(systemId, CommonConstant.SYSTEM_ID_FO) && StringUtils.equals(bussinessId,CommonConstant.FO_INFO_FILE)){
                pageSize = "A2";
            } else if (StringUtils.equals(systemId, CommonConstant.SYSTEM_ID_AOSR)){
                pageSize = "A2";
            }
        }
        return pageSize;
    }
}
